package com.clei.utils;

import com.clei.utils.mqtt.DefaultMqttMsgCallback;
import com.clei.utils.mqtt.MqttManager;
import com.clei.utils.mqtt.MqttProperty;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * mqtt util
 *
 * @author Y
 * @date 2024-01-02
 **/
public class MqttUtil {

    /**
     * mqtt map
     * clientId -> MqttManager
     */
    private final static Map<String, MqttManager> MQTT_MAP = new ConcurrentHashMap<>(0);

    /**
     * 添加mqttManager
     *
     * @param mqttProperty mqttProperty
     * @param mqttCallback mqttCallback
     */
    public static void addManager(MqttProperty mqttProperty, DefaultMqttMsgCallback mqttCallback) {
        MqttManager mqttManager = new MqttManager(mqttProperty, mqttCallback);
        MQTT_MAP.put(mqttProperty.getClientId(), mqttManager);
    }

    /**
     * 发送消息
     *
     * @param clientId clientId
     * @param topic    topic
     * @param msg      msg
     */
    public static void publish(String clientId, String topic, String msg) {
        MqttManager mqttManager = MQTT_MAP.get(clientId);
        if (null != mqttManager) {
            mqttManager.publish(topic, msg);
        }
    }

    /**
     * 发送消息
     *
     * @param clientId clientId
     * @param topic    topic
     * @param msg      msg
     * @param qos      qos
     */
    public static void publish(String clientId, String topic, String msg, int qos) {
        MqttManager mqttManager = MQTT_MAP.get(clientId);
        if (null != mqttManager) {
            mqttManager.publish(topic, msg, qos);
        }
    }

    /**
     * 添加订阅
     *
     * @param clientId clientId
     * @param topic    topic
     */
    public static void subscribe(String clientId, String topic) {
        MqttManager mqttManager = MQTT_MAP.get(clientId);
        if (null != mqttManager) {
            mqttManager.subscribe(topic);
        }
    }

    /**
     * 添加订阅
     *
     * @param clientId clientId
     * @param topic    topic
     * @param qos      qos
     */
    public static void subscribe(String clientId, String topic, int qos) {
        MqttManager mqttManager = MQTT_MAP.get(clientId);
        if (null != mqttManager) {
            mqttManager.subscribe(topic, qos);
        }
    }
}
